﻿using System;
using System.IO;
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
using ExcelDataReader;
using System.Data;
using Newtonsoft.Json;
using Client.Base;

namespace Client.Editor
{
    public class Export_LanuageConfig : EditorWindow
    {
        private string excelPath = "";
        private bool existPath = true;
        private string[] excelFiles;
        private readonly int index_start = 1;
        private string gameSavePath => $"{Application.dataPath}/BundlePackage/pk_game/config";
        private string baseSavePath => $"{Application.dataPath}/Resources";
        
        // 样式变量
        private GUIStyle titleStyle;
        private GUIStyle headerStyle;
        private GUIStyle boxStyle;
        private GUIStyle buttonStyle;
        private GUIStyle exportButtonStyle;
        private GUIStyle exportAllButtonStyle;
        private GUIStyle pathLabelStyle;
        private GUIStyle fileNameStyle;
        private GUIStyle sectionHeaderStyle;
        
        // 滚动位置
        private Vector2 scrollPosition;
        
        // 颜色定义
        private readonly Color primaryColor = new Color(0.8f, 0.4f, 0.1f);
        private readonly Color successColor = new Color(0.2f, 0.7f, 0.3f);
        private readonly Color backgroundColor = new Color(0.98f, 0.96f, 0.92f);
  
        public static void ShowWindow()
        {
            Export_LanuageConfig window = GetWindow<Export_LanuageConfig>("🌍 导出多语言配置");
            window.minSize = new Vector2(450, 350);
            window.Show();
        }

        private void OnEnable()
        {
            excelPath = Path.Combine(Path.GetDirectoryName(Application.dataPath), "Excel", "Language");
            if (!Directory.Exists(excelPath))
            {
                existPath = false;
            }
            else
            {
                excelFiles = Directory.GetFiles(excelPath, "*.xlsx");
                if (excelFiles == null || excelFiles.Length == 0)
                {
                    Debug.LogError($"Excel目录中不存在xlsx文件: {excelPath}");
                }
            }
        }
        
        private void InitializeStyles()
        {
            // 标题样式
            titleStyle = new GUIStyle(EditorStyles.largeLabel)
            {
                fontSize = 18,
                fontStyle = FontStyle.Bold,
                alignment = TextAnchor.MiddleCenter
            };
            titleStyle.normal.textColor = primaryColor;
            
            // 头部样式
            headerStyle = new GUIStyle(EditorStyles.label)
            {
                fontSize = 12,
                fontStyle = FontStyle.Italic,
                alignment = TextAnchor.MiddleCenter
            };
            headerStyle.normal.textColor = new Color(0.5f, 0.5f, 0.5f);
            
            // 主盒子样式
            boxStyle = new GUIStyle(GUI.skin.box)
            {
                padding = new RectOffset(20, 20, 15, 15),
                margin = new RectOffset(10, 10, 8, 8)
            };
            
            // 基础按钮样式
            buttonStyle = new GUIStyle(GUI.skin.button)
            {
                fontSize = 12,
                fontStyle = FontStyle.Normal,
                fixedHeight = 32,
                padding = new RectOffset(15, 15, 5, 5),
                margin = new RectOffset(5, 5, 3, 3)
            };
            
            // 导出按钮样式
            exportButtonStyle = new GUIStyle(buttonStyle)
            {
                fixedHeight = 32,
                padding = new RectOffset(15, 15, 5, 5)
            };
            
            // 导出全部按钮样式
            exportAllButtonStyle = new GUIStyle(exportButtonStyle)
            {
                fontSize = 14,
                fontStyle = FontStyle.Bold,
                fixedHeight = 40,
                padding = new RectOffset(25, 25, 8, 8)
            };
            
            // 路径标签样式
            pathLabelStyle = new GUIStyle(EditorStyles.label)
            {
                wordWrap = true,
                alignment = TextAnchor.MiddleLeft,
                fontSize = 11,
                padding = new RectOffset(5, 5, 2, 2)
            };
            pathLabelStyle.normal.textColor = new Color(0.4f, 0.4f, 0.4f);
            
            // 文件名样式
            fileNameStyle = new GUIStyle(EditorStyles.label)
            {
                fontSize = 13,
                fontStyle = FontStyle.Bold,
                alignment = TextAnchor.MiddleLeft
            };
           fileNameStyle.normal.textColor = new Color(145/255.0f, 253/255.0f, 174/255.0f);
            
            // 分区标题样式
            sectionHeaderStyle = new GUIStyle(EditorStyles.label)
            {
                fontSize = 14,
                fontStyle = FontStyle.Bold,
                alignment = TextAnchor.MiddleLeft,
                padding = new RectOffset(0, 0, 5, 5)
            };
            sectionHeaderStyle.normal.textColor = new Color(0.6f, 0.3f, 0.1f);
        }

        private void OnGUI()
        {
            // 设置背景色
            GUI.backgroundColor = backgroundColor;
            
            // 初始化样式
            if (titleStyle == null)
            {
                InitializeStyles();
            }
            
            // 主滚动视图
            scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);
            {
                // 绘制标题区域
                DrawHeader();
                
                if (!existPath)
                {
                    DrawErrorBox();
                }
                else
                {
                    // 绘制内容区域
                    DrawContent();
                }
            }
            EditorGUILayout.EndScrollView();
            
            // 重置背景色
            GUI.backgroundColor = Color.white;
        }
        
        private void DrawHeader()
        {
            EditorGUILayout.Space(15);
            
            // 主标题
            EditorGUILayout.BeginVertical();
            EditorGUILayout.LabelField("🌍 多语言配置导出工具", titleStyle);
            EditorGUILayout.LabelField("将Excel多语言表导出为游戏可用的语言包", headerStyle);
            EditorGUILayout.EndVertical();
            
            EditorGUILayout.Space(20);
        }
        
        private void DrawErrorBox()
        {
            EditorGUILayout.BeginVertical(boxStyle);
            {
                EditorGUILayout.HelpBox($"❌ Excel目录不存在", MessageType.Error);
                
                EditorGUILayout.Space(10);
                EditorGUILayout.LabelField($"路径: {excelPath}", pathLabelStyle);
                EditorGUILayout.Space(15);
                
                EditorGUILayout.BeginHorizontal();
                GUILayout.FlexibleSpace();
                if (GUILayout.Button("关闭窗口", exportButtonStyle, GUILayout.Width(120)))
                {
                    Close();
                }
                GUILayout.FlexibleSpace();
                EditorGUILayout.EndHorizontal();
            }
            EditorGUILayout.EndVertical();
        }
        
        private void DrawContent()
        {
            // 路径信息区域
            DrawPathInfo();
            
            EditorGUILayout.Space(20);
            
            // 文件列表区域
            DrawFileListSection();
            
            EditorGUILayout.Space(15);
            
            // 操作按钮区域
            DrawActionButtons();
        }
        
        private void DrawPathInfo()
        {
            EditorGUILayout.BeginVertical(boxStyle);
            {
                EditorGUILayout.LabelField("📁 路径信息", sectionHeaderStyle);
                EditorGUILayout.Space(12);
                
                EditorGUILayout.BeginVertical(GUI.skin.box);
                {
                    EditorGUILayout.LabelField("Excel目录:", EditorStyles.boldLabel);
                    EditorGUILayout.Space(3);
                    EditorGUILayout.LabelField(excelPath, pathLabelStyle);
                }
                EditorGUILayout.EndVertical();
                
                EditorGUILayout.Space(8);
                
                EditorGUILayout.BeginVertical(GUI.skin.box);
                {
                    EditorGUILayout.LabelField("游戏配置目录:", EditorStyles.boldLabel);
                    EditorGUILayout.Space(3);
                    EditorGUILayout.LabelField(gameSavePath, pathLabelStyle);
                }
                EditorGUILayout.EndVertical();
                
                EditorGUILayout.Space(5);
                
                EditorGUILayout.BeginVertical(GUI.skin.box);
                {
                    EditorGUILayout.LabelField("基础资源目录:", EditorStyles.boldLabel);
                    EditorGUILayout.Space(3);
                    EditorGUILayout.LabelField(baseSavePath, pathLabelStyle);
                }
                EditorGUILayout.EndVertical();
                
                // 文件统计
                EditorGUILayout.Space(10);
                EditorGUILayout.BeginHorizontal();
                GUILayout.FlexibleSpace();
                EditorGUILayout.LabelField($"发现 {excelFiles?.Length ?? 0} 个Excel文件", headerStyle);
                GUILayout.FlexibleSpace();
                EditorGUILayout.EndHorizontal();
            }
            EditorGUILayout.EndVertical();
        }
        
        private void DrawFileListSection()
        {
            EditorGUILayout.BeginVertical(boxStyle);
            {
                EditorGUILayout.LabelField("🗂️ 语言文件列表", sectionHeaderStyle);
                EditorGUILayout.Space(10);
                
                if (excelFiles == null || excelFiles.Length == 0)
                {
                    EditorGUILayout.HelpBox("📭 未找到Excel文件", MessageType.Info);
                    return;
                }
                
                // 文件列表
                foreach (var file in excelFiles)
                {
                    DrawFileItem(file);
                }
            }
            EditorGUILayout.EndVertical();
        }
        
        private void DrawFileItem(string file)
        {
            EditorGUILayout.BeginHorizontal();
            {
                // 文件信息
                EditorGUILayout.BeginVertical(GUILayout.Width(300));
                {
                    EditorGUILayout.LabelField("📄 " + Path.GetFileName(file), fileNameStyle);
                    EditorGUILayout.LabelField(Path.GetDirectoryName(file), pathLabelStyle);
                }
                EditorGUILayout.EndVertical();
                
                GUILayout.FlexibleSpace();
                
                // 导出按钮
                Color originalColor = GUI.color;
                GUI.color = new Color(0.8f, 0.5f, 0.2f);
                if (GUILayout.Button("导出语言包", exportButtonStyle, GUILayout.Width(100)))
                {
                    ReadFile(file);
                    AssetDatabase.Refresh();
                    ShowNotification(new GUIContent($"✅ 已导出: {Path.GetFileName(file)}"));
                    Debug.Log($"🌍 多语言导出完成: {Path.GetFileName(file)}");
                }
                GUI.color = originalColor;
            }
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.Space(5);
        }
        
        private void DrawActionButtons()
        {
            EditorGUILayout.BeginVertical(boxStyle);
            {
                EditorGUILayout.LabelField("⚡ 批量操作", sectionHeaderStyle);
                EditorGUILayout.Space(15);
                
                EditorGUILayout.BeginHorizontal();
                GUILayout.FlexibleSpace();
                
                // 导出全部按钮
                Color originalColor = GUI.color;
                GUI.color = successColor;
                if (GUILayout.Button($"🚀 导出全部文件 ({excelFiles?.Length ?? 0})", exportAllButtonStyle, GUILayout.Width(250)))
                {
                    if (EditorUtility.DisplayDialog("确认批量导出", 
                        $"确定要导出所有 {excelFiles.Length} 个语言文件吗？\n\n这将生成多个语言包文件。", 
                        "确定导出", "取消"))
                    {
                        int successCount = 0;
                        foreach (var file in excelFiles)
                        {
                            try
                            {
                                ReadFile(file);
                                successCount++;
                                Debug.Log($"🌍 多语言导出完成: {Path.GetFileName(file)}");
                            }
                            catch (Exception ex)
                            {
                                Debug.LogError($"❌ 导出失败 {Path.GetFileName(file)}: {ex.Message}");
                            }
                        }
                        AssetDatabase.Refresh();
                        ShowNotification(new GUIContent($"✅ 导出完成: {successCount}/{excelFiles.Length} 个文件"));
                    }
                }
                GUI.color = originalColor;
                
                GUILayout.FlexibleSpace();
                EditorGUILayout.EndHorizontal();
                
                EditorGUILayout.Space(5);
                
                // 刷新按钮
                EditorGUILayout.BeginHorizontal();
                GUILayout.FlexibleSpace();
                if (GUILayout.Button("🔄 刷新文件列表", buttonStyle, GUILayout.Width(150)))
                {
                    OnEnable();
                    Repaint();
                }
                GUILayout.FlexibleSpace();
                EditorGUILayout.EndHorizontal();
            }
            EditorGUILayout.EndVertical();
        }

        private void ReadFile(string file)
        {
            try
            {
                using (var stream = File.Open(file, FileMode.Open, FileAccess.Read))
                {
                    using (var reader = ExcelReaderFactory.CreateReader(stream))
                    {
                        var result = reader.AsDataSet();
                        DataTable table = result.Tables[0];
                        int languageCount = table.Rows[0].ItemArray.Length - 1;
                        ExcelInfo[] infos = new ExcelInfo[languageCount];
                        
                        // 初始化语言信息
                        for (int i = 0; i < infos.Length; i++)
                        {
                            string name = table.Rows[0].ItemArray[i + 1].ToString();
                            infos[i] = new ExcelInfo(name);
                        }
                        
                        // 填充语言数据
                        for (int i = 0; i < infos.Length; i++)
                        {
                            for (int j = index_start; j < table.Rows.Count; j++)
                            {
                                CLanguage lang = new CLanguage
                                {
                                    key = table.Rows[j][0].ToString(),
                                    content = table.Rows[j][i + 1].ToString()
                                };
                                infos[i].ls.Add(lang);
                            }
                        }

                        // 导出语言文件
                        for (int i = 0; i < infos.Length; i++)
                        {
                            string data = JsonConvert.SerializeObject(infos[i].ls);
                            string path = table.TableName.Trim().Equals("base") ? baseSavePath : gameSavePath;
                            
                            if (!Directory.Exists(path))
                            {
                                Directory.CreateDirectory(path);
                            }
                            
                            string realPath = $"{path}/lan_{infos[i].name}.bytes";
                            File.WriteAllText(realPath, data, System.Text.Encoding.UTF8);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.LogError($"❌ 导出语言文件 {Path.GetFileName(file)} 时出错: {ex.Message}");
                EditorUtility.DisplayDialog("导出错误", $"导出 {Path.GetFileName(file)} 时出错:\n{ex.Message}", "确定");
            }
        }

        private class ExcelInfo
        {
            public string name { get; set; }
            public List<CLanguage> ls { get; set; }
            
            public ExcelInfo(string name)
            {
                this.name = name;
                ls = new List<CLanguage>();
            }
        }
    }
}